package com.ktg.mes.qc.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.ktg.common.exception.ServiceException;
import com.ktg.common.utils.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ktg.common.utils.SecurityUtils;
import com.ktg.common.utils.bean.BeanValidators;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ktg.mes.qc.mapper.QcItemTestingResultMapper;
import com.ktg.mes.qc.domain.QcItemTestingResult;
import com.ktg.mes.qc.service.IQcItemTestingResultService;

import javax.validation.Validator;

import static com.ktg.mes.qc.mapper.QcItemTestingResultMapper.*;


/**
 * 产品检测记录Service业务层处理
 *
 * @author byteco
 * @date 2023-01-16
 */
@Service
public class QcItemTestingResultServiceImpl extends ServiceImpl<QcItemTestingResultMapper, QcItemTestingResult> implements IQcItemTestingResultService
{

    @Autowired
    protected Validator validator;


    /**
     * 查询产品检测记录
     *
     * @param entity 产品检测记录
     * @param page 分页对象
     * @return 产品检测记录
     */
    @Override
    public IPage<QcItemTestingResult> queryPageList(QcItemTestingResult entity, Page<QcItemTestingResult> page) {
//        if (entity.getQualityJudgment() != null && entity.getQualityJudgment().length() == 0){
//            entity.setQualityJudgment(null);
//        }
        QueryWrapper<QcItemTestingResult> lqw = new QueryWrapper<QcItemTestingResult>(entity);
        lqw.orderByDesc("create_time");
        IPage<QcItemTestingResult> pageList = this.page(page, lqw);
        return pageList;
    }

    /**
     * 查询产品检测记录
     *
     * @param entity 产品检测记录
     * @return 产品检测记录
     */
    @Override
    public List<QcItemTestingResult> queryList(QcItemTestingResult entity) {
        QueryWrapper<QcItemTestingResult> lqw = new QueryWrapper<QcItemTestingResult>(entity);
        lqw.orderByDesc("create_time");
        return this.list(lqw);
    }

    public QcItemTestingResult getInfo(Long id)
    {
        return this.getById(id);
    }


    /**
     * 新增产品检测记录
     *
     * @param entity 产品检测记录
     * @return 结果
     */
    @Override
    public void insert(QcItemTestingResult entity)
    {
        entity.setCreateBy(SecurityUtils.getUsername());
        entity.setCreateTime(DateUtils.getNowDate());
        this.save(entity);
    }

    /**
     * 修改产品检测记录
     *
     * @param entity 产品检测记录
     * @return 结果
     */
    @Override
    public boolean update(QcItemTestingResult entity)
    {
        entity.setUpdateBy(SecurityUtils.getUsername());
        entity.setUpdateTime(DateUtils.getNowDate());
        return this.updateById(entity);
    }

    /**
     * 批量删除产品检测记录
     *
     * @param recordIds 需要删除的产品检测记录主键
     * @return 结果
     */
    @Override
    public boolean delete(Long[] recordIds)
    {

        return this.removeByIds(Arrays.asList(recordIds));
    }

    /**
     * 删除产品检测记录信息
     *
     * @param recordId 产品检测记录主键
     * @return 结果
     */
    @Override
    public boolean delete(Long recordId)
    {
        return this.removeById(recordId);
    }

    /**
     * 产品质量总结
     * @param month
     * @return
     */
    public List<Map> selectProductQualitySummary(String month){
        return getBaseMapper().selectProductQualitySummary(month);
    };

    /**
     * 产品质量总结
     * @param month
     * @return
     */
    public QcItemTestingResult selectQcItemTestingByBatchNo(String batchNo){
        return getBaseMapper().selectQcItemTestingByBatchNo(batchNo);
    };


    /**
     * 导入产品检测记录数据
     *
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importTable(List<QcItemTestingResult> tableList, Boolean isUpdateSupport)
    {
        if (com.ktg.common.utils.StringUtils.isNull(tableList) || tableList.size() == 0)
        {
            throw new ServiceException("导入产品检测记录数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (QcItemTestingResult qcItemTestingResult : tableList)
        {
            try
            {
                // 验证是否存在这个用户
                QcItemTestingResult u = getBaseMapper().selectQcItemTestingByBatchNo(qcItemTestingResult.getBatchNo());
                if (com.ktg.common.utils.StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, qcItemTestingResult);
                    successNum++;
                    this.insert(qcItemTestingResult);
                    successMsg.append("<br/>" + successNum + "、型号 " + qcItemTestingResult.getSpecification() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    if(SecurityUtils.isAdmin(qcItemTestingResult.getRecordId())){
                        failureMsg.append("<br/>" + successNum + "、型号 " + qcItemTestingResult.getSpecification() + " 不允许更新");
                        failureNum++;
                        continue;
                    }
                    BeanValidators.validateWithException(validator, qcItemTestingResult);
                    this.update(qcItemTestingResult);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、型号 " + qcItemTestingResult.getSpecification() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、型号 " + qcItemTestingResult.getSpecification() + " 已存在");

                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、型号 " + qcItemTestingResult.getSpecification() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    private LambdaQueryWrapper<QcItemTestingResult> buildQueryWrapper(QcItemTestingResult entity) {
        LambdaQueryWrapper<QcItemTestingResult> lqw = Wrappers.lambdaQuery();
                    lqw.eq(StringUtils.isNotBlank(entity.getItemId()), QcItemTestingResult::getItemId, entity.getItemId());
                    lqw.eq(StringUtils.isNotBlank(entity.getTaskId()), QcItemTestingResult::getTaskId, entity.getTaskId());
                    lqw.like(StringUtils.isNotBlank(entity.getItemName()), QcItemTestingResult::getItemName, entity.getItemName());
                    lqw.eq(StringUtils.isNotBlank(entity.getSpecification()), QcItemTestingResult::getSpecification, entity.getSpecification());
                    lqw.eq(entity.getViscosity() != null, QcItemTestingResult::getViscosity, entity.getViscosity());
                    lqw.eq(entity.getDatePruduct() != null, QcItemTestingResult::getDatePruduct, entity.getDatePruduct());
                    lqw.eq(StringUtils.isNotBlank(entity.getBatchNo()), QcItemTestingResult::getBatchNo, entity.getBatchNo());
                    lqw.eq(StringUtils.isNotBlank(entity.getBarrelNo()), QcItemTestingResult::getBarrelNo, entity.getBarrelNo());
                    lqw.eq(StringUtils.isNotBlank(entity.getAppearance()), QcItemTestingResult::getAppearance, entity.getAppearance());
                    lqw.eq(entity.getWeight() != null, QcItemTestingResult::getWeight, entity.getWeight());
                    lqw.eq(entity.getWeightReal() != null, QcItemTestingResult::getWeightReal, entity.getWeightReal());
                    lqw.eq(entity.getDissolutionRatio() != null, QcItemTestingResult::getDissolutionRatio, entity.getDissolutionRatio());
                    lqw.eq(entity.getViscosityGrinding() != null, QcItemTestingResult::getViscosityGrinding, entity.getViscosityGrinding());
                    lqw.eq(entity.getViscosityBeforePackaging() != null, QcItemTestingResult::getViscosityBeforePackaging, entity.getViscosityBeforePackaging());
                    lqw.eq(entity.getSolventReplenishment() != null, QcItemTestingResult::getSolventReplenishment, entity.getSolventReplenishment());
                    lqw.eq(entity.getViscosityPackaging() != null, QcItemTestingResult::getViscosityPackaging, entity.getViscosityPackaging());
                    lqw.eq(entity.getDatePackaging() != null, QcItemTestingResult::getDatePackaging, entity.getDatePackaging());
                    lqw.eq(StringUtils.isNotBlank(entity.getQualityJudgment()), QcItemTestingResult::getQualityJudgment, entity.getQualityJudgment());
                    lqw.eq(entity.getTestTemperature1() != null, QcItemTestingResult::getTestTemperature1, entity.getTestTemperature1());
                    lqw.eq(entity.getViscosity4DayVt06() != null, QcItemTestingResult::getViscosity4DayVt06, entity.getViscosity4DayVt06());
                    lqw.eq(entity.getViscosityCorrected1() != null, QcItemTestingResult::getViscosityCorrected1, entity.getViscosityCorrected1());
                    lqw.eq(entity.getTestTemperature2() != null, QcItemTestingResult::getTestTemperature2, entity.getTestTemperature2());
                    lqw.eq(entity.getViscosity10DayVt06() != null, QcItemTestingResult::getViscosity10DayVt06, entity.getViscosity10DayVt06());
                    lqw.eq(entity.getViscosityCorrected2() != null, QcItemTestingResult::getViscosityCorrected2, entity.getViscosityCorrected2());
                    lqw.eq(entity.getGrindingFineness1() != null, QcItemTestingResult::getGrindingFineness1, entity.getGrindingFineness1());
                    lqw.eq(entity.getGrindingPitting1() != null, QcItemTestingResult::getGrindingPitting1, entity.getGrindingPitting1());
                    lqw.eq(entity.getGrindingFineness2() != null, QcItemTestingResult::getGrindingFineness2, entity.getGrindingFineness2());
                    lqw.eq(entity.getGrindingPitting2() != null, QcItemTestingResult::getGrindingPitting2, entity.getGrindingPitting2());
                    lqw.eq(entity.getPackagingFineness() != null, QcItemTestingResult::getPackagingFineness, entity.getPackagingFineness());
                    lqw.eq(entity.getPackagingPitting() != null, QcItemTestingResult::getPackagingPitting, entity.getPackagingPitting());
                    lqw.eq(entity.getHardness() != null, QcItemTestingResult::getHardness, entity.getHardness());
        return lqw;
    }
}
